package com.smart.wap.service;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import com.smart.common.cache.CacheService;
import com.smart.common.entities.core.Page;
import com.smart.manager.member.entities.enums.CoinAccountEvent;
import com.smart.manager.member.entities.enums.SaleBill;
import com.smart.manager.member.entities.enums.SaleStatus;
import com.smart.manager.member.entities.models.MemberMaterialPig;
import com.smart.manager.member.entities.models.MemberPigSale;
import com.smart.manager.member.entities.models.MemberPigSaleBill;
import com.smart.manager.member.entities.models.query.QMemberMaterialPig;
import com.smart.manager.member.entities.models.query.QMemberPigSale;
import com.smart.manager.member.entities.models.query.QMemberPigSaleBill;
import com.smart.manager.member.entities.views.MemberPigView;
import com.smart.manager.member.entities.views.MemberView;
import com.smart.manager.member.repository.MemberAccountRepository;
import com.smart.utils.MemberAcl;
import com.smart.wap.bodys.SaleBody;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
@Slf4j
public class SaleService {

    private final MemberAccountRepository memberAccountRepository;
    private final CacheService cacheService;


    /**
     * 添加售卖信息
     * <p>
     * 1.判断当前猪仔是否已被出售
     * 2.判断是否是自己的猪
     */
    public void addSale(SaleBody.EditBody body) {
        Long loginId = MemberAcl.getLoginId();
        MemberMaterialPig materialPig = new QMemberMaterialPig().code.eq(body.getPigCode()).setMaxRows(1).findOne();
        MemberPigSale pigSale = new QMemberPigSale().pigId.code.eq(body.getPigCode()).setMaxRows(1).findOne();
        //1.判断当前猪仔是否已被出售
        if (ObjUtil.isNotNull(pigSale)) {
            Assert.isTrue(pigSale.getStatus().equals(SaleStatus.Sold), "当前猪仔正在售卖中请勿重复提交！");
        }
        //2.判断是否有猪
        Assert.isFalse(ObjUtil.isNull(materialPig), "未找到当前猪猪！");
        //3.判断是否是自己的猪
        LocalDateTime date = LocalDateTime.now();
        Assert.isTrue(materialPig.getMember().getId().equals(loginId), "您不能操作别人的猪猪！");
        long id = IdUtil.getSnowflakeNextId();
        MemberPigSale memberPigSale = new MemberPigSale()
                .setSellerId(new MemberView().setId(loginId))
                .setPigId(new MemberPigView().setId(materialPig.getId()))
                .setPrice(body.getPrice())
                .setListingTime(date)
                .setStatus(SaleStatus.Available);
        memberPigSale.setId(id);
        memberPigSale.insert();
    }

    /**
     *
     * 2.通知消息
     * @param body
     */
    public void purchaseSale(SaleBody.PurchaseBody body) {
        Long loginId = MemberAcl.getLoginId();
        LocalDateTime date = LocalDateTime.now();
        MemberPigSale memberPigSale = new QMemberPigSale().id.eq(body.getSaleId()).setMaxRows(1).findOne();
        Assert.isFalse(ObjUtil.isNull(memberPigSale), "购买的猪猪不存在！");
        Assert.isTrue(memberPigSale.getStatus().equals(SaleStatus.Available), "您来晚啦，你选中的猪猪被其他玩家抢走了或者已经失效啦");
        //扣钱
        BigDecimal price = memberPigSale.getPrice(); //钱

        memberAccountRepository.saveEvent(loginId, CoinAccountEvent.SHOPOUT, price.intValue(), "购买玩家猪猪");

        MemberMaterialPig materialPig = new QMemberMaterialPig().id.eq(memberPigSale.getPigId().getId()).setMaxRows(1).findOne();
        Assert.isFalse(ObjUtil.isNull(materialPig), "购买的猪仔不存在");

        //生成流水
        MemberPigSaleBill memberPigSaleBill = new MemberPigSaleBill()
                .setSaleId(memberPigSale.getId())
                .setMemberId(memberPigSale.getSellerId())
                .setPrice(memberPigSale.getPrice())
                .setPigId(memberPigSale.getPigId())
                .setTransactionTime(date).setSaleBill(SaleBill.L2);
        MemberPigSaleBill pigSaleBill = BeanUtil.copyProperties(memberPigSaleBill, MemberPigSaleBill.class);
        memberPigSale.insert(); //出售记录
        pigSaleBill.setSaleBill(SaleBill.L1).setMemberId(new MemberView().setId(loginId)).setTransactionTime(date);
        pigSaleBill.insert();  //购买记录
        //设置猪仔
        memberPigSale.setStatus(SaleStatus.Sold).setBuyerId(pigSaleBill.getMemberId()).setPurchaseTime(date).update();
        //修改猪仔归属人
        materialPig.setMember(pigSaleBill.getMemberId()).setCloseMember(null).update();
    }

    /**
     * 查找售卖列表
     * @param search
     * @return {@link Page}<{@link MemberPigSale}>
     */
    public Page<MemberPigSale> getPageList(SaleBody.SearchBody search) {
        QMemberPigSale query = new QMemberPigSale();
        query.status.eq(SaleStatus.Available);
        query.order().id.desc();
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<MemberPigSale>().load(query.findPagedList());
    }


    /**
     * 获取购买流水
     * @param search
     * @return {@link Page}<{@link MemberPigSaleBill}>
     */
    public Page<MemberPigSaleBill> getBillList(SaleBody.SearchBody search){
        Long loginId = MemberAcl.getLoginId();
        QMemberPigSaleBill query = new QMemberPigSaleBill();
        query.memberId.id.eq(loginId);
        if (search.getIs()){
            query.saleBill.eq(SaleBill.L1);
        }else {
            query.saleBill.eq(SaleBill.L2);
        }
        query.order().id.desc();
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<MemberPigSaleBill>().load(query.findPagedList());
    }
}
